﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;

namespace Entangle
{
    class SymmetricKey
    {
        private byte[] iv;
        private byte[] key;
        private string id;

        public byte[] IV { get { return iv; } }
        public byte[] Key { get { return key; } }
        public string Id { get { return id; } }

        public SymmetricKey(string pId, byte[] pKey, byte[] pIv)
        {
            key = pKey;
            iv = pIv;
            id = pId;
        }

        public string ToXMLString(bool encryptForPartner)
        {
            byte[] hash = encryptForPartner ? (Cryptography.Instance.PartnerPublicKeyHash) : (Cryptography.Instance.PublicKeyHash);
            byte[] c_iv = encryptForPartner ? (Cryptography.Instance.RSAEncryptWithPartnerKey(iv)) : (Cryptography.Instance.RSAEncryptWithPrivateKey(iv));
            byte[] c_key = encryptForPartner ? (Cryptography.Instance.RSAEncryptWithPartnerKey(key)) : (Cryptography.Instance.RSAEncryptWithPrivateKey(key));
            string c_id = encryptForPartner ? (Cryptography.Instance.RSAEncryptWithPartnerKey(id)) : (Cryptography.Instance.RSAEncryptWithPrivateKey(id));

            XmlDocument xml = new XmlDocument();
            XmlElement xeSymmetricKey = xml.CreateElement("SymmetricKey");
            xeSymmetricKey.SetAttribute("UsedRSAHash", Convert.ToBase64String(hash));

            XmlElement xeID = xml.CreateElement("ID");
            xeID.InnerText = c_id;
            xeSymmetricKey.AppendChild(xeID);

            XmlElement xeIV = xml.CreateElement("IV");
            xeIV.InnerText = Convert.ToBase64String(c_iv);
            xeSymmetricKey.AppendChild(xeIV);

            XmlElement xeKey = xml.CreateElement("Key");
            xeKey.InnerText = Convert.ToBase64String(c_key);
            xeSymmetricKey.AppendChild(xeKey);

            xml.AppendChild(xeSymmetricKey);
            return xml.OuterXml;
        }
    }
}
